﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Dto;

namespace Happy.Domain
{
    /// <summary>
    /// 泛型版本的实体基类。
    /// </summary>
    public abstract class Entity<TId> : IEntity<TId>
    {
        private int? _requestedHashCode;

        /// <summary>
        /// 构造方法。
        /// </summary>
        protected Entity() { }

        /// <summary>
        /// 构造方法。
        /// </summary>
        protected Entity(TId id)
        {
            this.Id = id;
        }

        /// <summary>
        /// 主键。
        /// </summary>
        public TId Id
        {
            get;
            protected set;
        }

        /// <inheritdoc />
        public override Boolean Equals(object obj)
        {
            if (obj == null || !(obj is Entity<TId>))
            {
                return false;
            }

            if (object.ReferenceEquals(this, obj))
            {
                return true;
            }

            var item = (Entity<TId>)obj;

            return item.Id.Equals(this.Id);
        }

        /// <inheritdoc />
        public override int GetHashCode()
        {
            if (!_requestedHashCode.HasValue)
            {
                _requestedHashCode = this.Id.GetHashCode() ^ 31;
            }

            return _requestedHashCode.Value;
        }

        /// <inheritdoc />
        public static bool operator ==(Entity<TId> left, Entity<TId> right)
        {
            return object.Equals(left, null)
                ? (object.Equals(right, null))
                : left.Equals(right);
        }

        /// <inheritdoc />
        public static bool operator !=(Entity<TId> left, Entity<TId> right)
        {
            return !(left == right);
        }
    }
}
